<?php
// +----------------------------------------------------------------------
// |目录管理控制器
// +----------------------------------------------------------------------


namespace app\Api\controller;

use app\BaseController;
use think\facade\Db;

class HginData extends BaseController
{

    public function index()
    {
        $accessToken = $this->getAccessToken();
        if ($accessToken) {
            Db::name('shops')->where('id', '2')->update([
                'token' => $accessToken['access_token'] ?? '',
                'refresh_token' => $accessToken['refresh_token'] ?? ''
            ]);
            echo "获取成功并已保存: " . json_encode($accessToken) . "\n<br>";
        } else {
            echo "\n<br>使用授权码获取失败。";
        }
    }

    /**
     * 获取敦煌网Access Token的公共方法
     * @return string|false 成功返回Access Token，失败返回false
     */
    public function getAccessToken()
    {
        // 如果appKey或appSecret不存在，则保存到数据库       
        $appSecret = Db::name('shops')->where('id', '2')->field('sp_author')->find();
        $appSecret = json_decode($appSecret['sp_author'], true);
        $appKey = $appSecret['appKey'];
        $appSecret = $appSecret['appSecret'];

        // 动态获取当前请求的URL作为回调URL
        $redirectUri = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $scope = 'basic'; // 请求的权限范围

        // 检查URL中是否包含授权码
        if (isset($_GET['code'])) {
            $code = $_GET['code'];
            echo "获取到授权码：" . $code . "\n<br>";

            // 使用授权码获取Access Token
            $accessToken = $this->getAccessTokenByCode($appKey, $appSecret, $code, $redirectUri);
            return $accessToken;
        } else {
            // 如果没有授权码，则显示授权URL
            $authUrl = 'https://secure.dhgate.com/dop/oauth2/authorize?' .
                'response_type=code&' .
                'client_id=' . $appKey . '&' .
                'redirect_uri=' . urlencode($redirectUri) . '&' .
                'scope=' . $scope;

            header('Location: ' . $authUrl);
            exit;
        }
    }

    /**
     * 通过HTTP请求获取敦煌网Access Token
     * @param string $client_id 应用的APP Key
     * @param string $client_secret 应用的APP Secret
     * @param string $username 敦煌网用户名
     * @param string $password 敦煌网密码
     * @return string|false 成功返回Access Token，失败返回false
     */
    private function getAccessTokenByCode($appKey, $appSecret, $code, $redirectUri)
    {
        $tokenUrl = 'https://secure.dhgate.com/dop/oauth2/access_token';
        $params = [
            'grant_type' => 'authorization_code',
            'client_id' => $appKey,
            'client_secret' => $appSecret,
            'code' => $code,
            'redirect_uri' => $redirectUri,
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $tokenUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 生产环境请设置为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 生产环境请设置为2

        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'cURL Error: ' . curl_error($ch);
            return false;
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode == 200) {
            $data = json_decode($response, true);
            return $data ?? false;
        } else {
            echo "HTTP Error: " . $httpCode . ", Response: " . $response;
            return false;
        }
    }
}
